const express = require('express');
const router = express.Router();
const { authenticateToken } = require('./auth');
const db = require('../database/connection');

// Get referral info
router.get('/info', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;

    // Get user's referral code and referral link
    const user = await db.query(
      'SELECT referral_code, referred_by FROM users WHERE id = ?',
      [userId]
    );

    if (user.length === 0) {
      return res.status(404).json({ error: 'User not found' });
    }

    const referralCode = user[0].referral_code;
    const referredBy = user[0].referred_by;

    // Get referral statistics
    const stats = await db.query(
      `SELECT
         COUNT(DISTINCT r.id) as total_referrals,
         COALESCE(SUM(rr.reward_amount), 0) as total_referral_rewards,
         COUNT(DISTINCT CASE WHEN r.created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN r.id END) as referrals_this_week,
         COUNT(DISTINCT CASE WHEN r.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN r.id END) as referrals_this_month
       FROM users u
       LEFT JOIN users r ON u.referral_code = r.referred_by
       LEFT JOIN referral_rewards rr ON u.id = rr.referrer_id
       WHERE u.id = ?`,
      [userId]
    );

    // Get recent referrals
    const recentReferrals = await db.query(
      `SELECT r.wallet_address, r.created_at,
         COALESCE(SUM(rr.reward_amount), 0) as total_rewards
       FROM users r
       LEFT JOIN referral_rewards rr ON r.id = rr.referred_user_id AND rr.referrer_id = ?
       WHERE r.referred_by = ?
       GROUP BY r.id, r.wallet_address, r.created_at
       ORDER BY r.created_at DESC
       LIMIT 10`,
      [userId, user[0].referral_code]
    );

    // Get referral rewards history
    const rewardHistory = await db.query(
      `SELECT rr.reward_amount, rr.reward_type, rr.created_at,
             u.wallet_address as referred_user_address
       FROM referral_rewards rr
       JOIN users u ON rr.referred_user_id = u.id
       WHERE rr.referrer_id = ?
       ORDER BY rr.created_at DESC
       LIMIT 20`,
      [userId]
    );

    res.json({
      referralCode,
      referralLink: `${process.env.FRONTEND_URL || 'http://localhost:3000'}/register?ref=${referralCode}`,
      referredBy,
      stats: stats[0] || {
        total_referrals: 0,
        total_referral_rewards: 0,
        referrals_this_week: 0,
        referrals_this_month: 0
      },
      recentReferrals,
      rewardHistory
    });

  } catch (error) {
    console.error('Referral info error:', error);
    res.status(500).json({ error: 'Failed to fetch referral information' });
  }
});

// Validate referral code
router.get('/validate/:code', async (req, res) => {
  try {
    const { code } = req.params;

    if (!code) {
      return res.status(400).json({ error: 'Referral code is required' });
    }

    const referrer = await db.query(
      'SELECT id, wallet_address FROM users WHERE referral_code = ?',
      [code]
    );

    if (referrer.length === 0) {
      return res.status(404).json({ error: 'Invalid referral code' });
    }

    res.json({
      valid: true,
      referrer: {
        id: referrer[0].id,
        walletAddress: referrer[0].wallet_address
      }
    });

  } catch (error) {
    console.error('Referral validation error:', error);
    res.status(500).json({ error: 'Failed to validate referral code' });
  }
});

// Get referral tree
router.get('/tree', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;
    const { depth = 3 } = req.query;

    // Get user's referral code
    const user = await db.query(
      'SELECT referral_code FROM users WHERE id = ?',
      [userId]
    );

    if (user.length === 0) {
      return res.status(404).json({ error: 'User not found' });
    }

    const referralCode = user[0].referral_code;

    // Build referral tree recursively
    async function getReferralLevel(parentCode, currentDepth) {
      if (currentDepth <= 0) return [];

      const referrals = await db.query(
        `SELECT id, wallet_address, created_at,
           (SELECT COALESCE(SUM(amount), 0) FROM transactions WHERE user_id = users.id AND transaction_type = 'deposit') as total_deposited,
           (SELECT COALESCE(SUM(amount), 0) FROM user_balances WHERE user_id = users.id) as current_balance
         FROM users
         WHERE referred_by = ?
         ORDER BY created_at DESC`,
        [parentCode]
      );

      for (const referral of referrals) {
        referral.children = await getReferralLevel(referral.referral_code, currentDepth - 1);
      }

      return referrals;
    }

    const tree = await getReferralLevel(referralCode, parseInt(depth));

    res.json({
      tree,
      maxDepth: parseInt(depth),
      totalNodes: countTreeNodes(tree)
    });

  } catch (error) {
    console.error('Referral tree error:', error);
    res.status(500).json({ error: 'Failed to fetch referral tree' });
  }
});

// Get referral earnings summary
router.get('/earnings', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;
    const { period = 'all' } = req.query; // 'week', 'month', 'all'

    let dateFilter = '';
    switch (period) {
      case 'week':
        dateFilter = 'AND rr.created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)';
        break;
      case 'month':
        dateFilter = 'AND rr.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)';
        break;
      default:
        dateFilter = '';
    }

    const earnings = await db.query(
      `SELECT
         reward_type,
         COUNT(*) as reward_count,
         COALESCE(SUM(reward_amount), 0) as total_rewards,
         COALESCE(AVG(reward_amount), 0) as average_reward,
         MIN(created_at) as first_reward_date,
         MAX(created_at) as last_reward_date
       FROM referral_rewards rr
       WHERE rr.referrer_id = ? ${dateFilter}
       GROUP BY reward_type`,
      [userId]
    );

    const dailyEarnings = await db.query(
      `SELECT
         DATE(created_at) as date,
         SUM(reward_amount) as daily_rewards,
         COUNT(*) as reward_count
       FROM referral_rewards
       WHERE referrer_id = ? ${dateFilter}
       GROUP BY DATE(created_at)
       ORDER BY date DESC
       LIMIT 30`,
      [userId]
    );

    const topReferrals = await db.query(
      `SELECT
         u.wallet_address,
         u.created_at as referral_date,
         COALESCE(SUM(rr.reward_amount), 0) as total_rewards_from_user,
         COUNT(rr.id) as reward_count
       FROM users u
       LEFT JOIN referral_rewards rr ON u.id = rr.referred_user_id AND rr.referrer_id = ?
       WHERE u.referred_by = (SELECT referral_code FROM users WHERE id = ?)
       GROUP BY u.id, u.wallet_address, u.created_at
       ORDER BY total_rewards_from_user DESC
       LIMIT 10`,
      [userId, userId]
    );

    res.json({
      earnings,
      dailyEarnings,
      topReferrals,
      period
    });

  } catch (error) {
    console.error('Referral earnings error:', error);
    res.status(500).json({ error: 'Failed to fetch referral earnings' });
  }
});

// Helper function to count tree nodes
function countTreeNodes(tree) {
  let count = tree.length;
  for (const node of tree) {
    if (node.children && node.children.length > 0) {
      count += countTreeNodes(node.children);
    }
  }
  return count;
}

module.exports = router;